import { getToken, removeUserInfo, removeToken, getUserInfo, getRole } from '@/utils/auth'
import Vue from 'vue'
import VueRouter from 'vue-router'


Vue.use(VueRouter)

// const role = JSON.parse(getUserInfo).role

const routes = [

  {
    path: '/',
    name: 'layout',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    
    component: () => import('@/layout/index'),
    children:[
      // {
      //   path:'/',
      //   name:'user',
      //   component:() => import('@/views/components/user')
      // },
      {
        path:'/user',
        name:'user',
        component:() => import('@/views/components/user')
      },
      {
        path:'/address',
        name:'address',
        component:() => import('@/views/components/address')
      },
      {
        path:'/town/:id',
        name:'town',
        component:() => import('@/views/components/town')
      },
      {
        path:'/userAttendance/:id',
        name:'userAttendance',
        component:()=>import('@/views/components/userAttendance')
      },
      {
        path:'/attendance',
        name:'attendance',
        component:() => import('@/views/components/attendance')
      },
      {
        path:'/approver',
        name:'approver',
        component: () => import('@/views/components/approver')
      },
      {
        path:'/approverInfo',
        name:'approverInfo',
        component: () => import('@/views/components/approverInfo')
      }
    ]
  },
  {
    path: '/login',
    name:'login',
    component: () => import('@/views/login.vue')
  },
  {
    path: '/404',
    name:'404',
    component: () => import('@/views/404'),
   
  }
]



const router = new VueRouter({
  routes
})

router.beforeEach((to,from,next)=>{
  // 判断是否下个页面为登入页
  if(to.path === '/login'){
    removeToken()
    removeUserInfo()
    next()
  }else if(to.path === '/404'){
    next()
  }  else{
    // 判断是否有token值
    if(getToken()){
       if(to.path !== '/approverInfo'){
        if(getRole() == 0 || getRole() == 1){
          next()
        }else{
          next({path:'/404'})
        }
       }else{
        next()
       }
    }else{
      // 没有token值去登入界面
      next({path:'/login'})
    }
  }
})


export default router
